<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><meta name="generator" content="Hexo 5.4.0"><link rel="apple-touch-icon" sizes="180x180" href="/hexoblog/images/apple-touch-icon-next.png"><link rel="icon" type="image/png" sizes="32x32" href="/hexoblog/images/favicon-32x32-next.png"><link rel="icon" type="image/png" sizes="16x16" href="/hexoblog/images/favicon-16x16-next.png"><link rel="mask-icon" href="/hexoblog/images/logo.svg" color="#222"><link rel="stylesheet" href="/hexoblog/css/main.css"><link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free@5.15.3/css/all.min.css"><link rel="stylesheet" href="https://unpkg.com/animate.css@3.1.1/animate.min.css"><link rel="stylesheet" href="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css"><script class="hexo-configurations">var NexT=window.NexT||{},CONFIG={hostname:"linqiankun.github.io",root:"/hexoblog/",images:"/hexoblog/images",scheme:"Gemini",version:"8.3.0",exturl:!1,sidebar:{position:"left",display:"post",padding:18,offset:12},copycode:!0,bookmark:{enable:!0,color:"#222",save:"auto"},fancybox:!0,mediumzoom:!1,lazyload:!1,pangu:!0,comments:{style:"tabs",active:null,storage:!0,lazyload:!1,nav:null},motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"fadeInDown",post_body:"fadeInDown",coll_header:"fadeInLeft",sidebar:"fadeInUp"}},prism:!1,i18n:{placeholder:"搜索...",empty:"没有找到任何搜索结果：${query}",hits_time:"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",hits:"找到 ${hits} 个搜索结果"},path:"/hexoblog/search.xml",localsearch:{enable:!0,trigger:"auto",top_n_per_article:1,unescape:!1,preload:!1}}</script><meta name="description" content="my blogs"><meta property="og:type" content="website"><meta property="og:title" content="Study"><meta property="og:url" content="https://linqiankun.github.io/hexoblog/page/18/index.html"><meta property="og:site_name" content="Study"><meta property="og:description" content="my blogs"><meta property="og:locale" content="zh_CN"><meta property="article:author" content="九分石人"><meta property="article:tag" content="Java"><meta name="twitter:card" content="summary"><link rel="canonical" href="https://linqiankun.github.io/hexoblog/page/18/"><script class="page-configurations">CONFIG.page={sidebar:"",isHome:!0,isPost:!1,lang:"zh-CN"}</script><title>Study</title><noscript><style>body{margin-top:2rem}.use-motion .collection-header,.use-motion .comments,.use-motion .menu-item,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header,.use-motion .sidebar{visibility:visible}.use-motion .footer,.use-motion .header,.use-motion .site-brand-container .toggle{opacity:initial}.use-motion .custom-logo-image,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line{transform:scaleX(1)}.search-pop-overlay,.sidebar-nav{display:none}.sidebar-panel{display:block}</style></noscript><link rel="alternate" href="/hexoblog/atom.xml" title="Study" type="application/atom+xml"><style>.darkmode--activated{--body-bg-color:#282828;--content-bg-color:#333;--card-bg-color:#555;--text-color:#ccc;--blockquote-color:#bbb;--link-color:#ccc;--link-hover-color:#eee;--brand-color:#ddd;--brand-hover-color:#ddd;--table-row-odd-bg-color:#282828;--table-row-hover-bg-color:#363636;--menu-item-bg-color:#555;--btn-default-bg:#222;--btn-default-color:#ccc;--btn-default-border-color:#555;--btn-default-hover-bg:#666;--btn-default-hover-color:#ccc;--btn-default-hover-border-color:#666;--highlight-background:#282b2e;--highlight-foreground:#a9b7c6;--highlight-gutter-background:#34393d;--highlight-gutter-foreground:#9ca9b6}.darkmode--activated img{opacity:.75}.darkmode--activated img:hover{opacity:.9}.darkmode--activated code{color:#69dbdc;background:0 0}button.darkmode-toggle{z-index:9999}.darkmode-ignore,img{display:flex!important}.beian img{display:inline-block!important}</style></head><body itemscope itemtype="http://schema.org/WebPage" class="use-motion"><div class="headband"></div><main class="main"><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-container"><div class="site-nav-toggle"><div class="toggle" aria-label="切换导航栏" role="button"><span class="toggle-line"></span> <span class="toggle-line"></span> <span class="toggle-line"></span></div></div><div class="site-meta"><a href="/hexoblog/" class="brand" rel="start"><i class="logo-line"></i><h1 class="site-title">Study</h1><i class="logo-line"></i></a><p class="site-subtitle" itemprop="description">好好学习，天天向上！</p></div><div class="site-nav-right"><div class="toggle popup-trigger"><i class="fa fa-search fa-fw fa-lg"></i></div></div></div><nav class="site-nav"><ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/hexoblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/hexoblog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/hexoblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/hexoblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/hexoblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-sitemap"><a href="/hexoblog/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-search"><a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索</a></li></ul></nav><div class="search-pop-overlay"><div class="popup search-popup"><div class="search-header"><span class="search-icon"><i class="fa fa-search"></i></span><div class="search-input-container"><input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input"></div><span class="popup-btn-close" role="button"><i class="fa fa-times-circle"></i></span></div><div class="search-result-container no-result"><div class="search-result-icon"><i class="fa fa-spinner fa-pulse fa-5x"></i></div></div></div></div></div><div class="toggle sidebar-toggle" role="button"><span class="toggle-line"></span> <span class="toggle-line"></span> <span class="toggle-line"></span></div><aside class="sidebar"><div class="sidebar-inner sidebar-overview-active"><ul class="sidebar-nav"><li class="sidebar-nav-toc">文章目录</li><li class="sidebar-nav-overview">站点概览</li></ul><div class="sidebar-panel-container"><div class="post-toc-wrap sidebar-panel"></div><div class="site-overview-wrap sidebar-panel"><div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" alt="九分石人" src="/hexoblog/images/avatar.png"><p class="site-author-name" itemprop="name">九分石人</p><div class="site-description" itemprop="description">my blogs</div></div><div class="site-state-wrap site-overview-item animated"><nav class="site-state"><div class="site-state-item site-state-posts"><a href="/hexoblog/archives/"><span class="site-state-item-count">239</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/hexoblog/categories/"><span class="site-state-item-count">35</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/hexoblog/tags/"><span class="site-state-item-count">64</span> <span class="site-state-item-name">标签</span></a></div></nav></div><div class="links-of-author site-overview-item animated"><span class="links-of-author-item"><a href="https://github.com/linqiankun" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;linqiankun" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a> </span><span class="links-of-author-item"><a href="linqiankun:191580378@qq.com" title="E-Mail → linqiankun:191580378@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a> </span><span class="links-of-author-item"><a href="https://weibo.com/jiufenshiren" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;jiufenshiren" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a> </span><span class="links-of-author-item"><a href="/hexoblog/atom.xml" title="Rss → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>Rss</a></span></div><div class="cc-license site-overview-item animated" itemprop="license"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/hexoblog/images/cc-by-nc-sa.svg" alt="Creative Commons"></a></div><div class="links-of-blogroll site-overview-item animated"><div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="http://124.222.164.140:3001/workspace/hexoblog" title="http:&#x2F;&#x2F;124.222.164.140:3001&#x2F;workspace&#x2F;hexoblog" rel="noopener" target="_blank">AnythingLLM</a></li><li class="links-of-blogroll-item"><a href="https://www.yuque.com/jiufenshiren" title="https:&#x2F;&#x2F;www.yuque.com&#x2F;jiufenshiren" rel="noopener" target="_blank">YuQue</a></li><li class="links-of-blogroll-item"><a href="https://github.com/LinQiankun" title="https:&#x2F;&#x2F;github.com&#x2F;LinQiankun" rel="noopener" target="_blank">Github</a></li><li class="links-of-blogroll-item"><a href="https://gitee.com/linqiankun" title="https:&#x2F;&#x2F;gitee.com&#x2F;linqiankun" rel="noopener" target="_blank">Gitee</a></li><li class="links-of-blogroll-item"><a href="https://my.oschina.net/linqiankun" title="https:&#x2F;&#x2F;my.oschina.net&#x2F;linqiankun" rel="noopener" target="_blank">OsChina</a></li><li class="links-of-blogroll-item"><a href="https://segmentfault.com/u/jiufenshiren" title="https:&#x2F;&#x2F;segmentfault.com&#x2F;u&#x2F;jiufenshiren" rel="noopener" target="_blank">Segmentfault</a></li><li class="links-of-blogroll-item"><a href="https://juejin.cn/user/3263006243306205" title="https:&#x2F;&#x2F;juejin.cn&#x2F;user&#x2F;3263006243306205" rel="noopener" target="_blank">Juejin</a></li><li class="links-of-blogroll-item"><a href="https://blog.csdn.net/qq_36985536?spm=1010.2135.3001.5421" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_36985536?spm&#x3D;1010.2135.3001.5421" rel="noopener" target="_blank">CSDN</a></li><li class="links-of-blogroll-item"><a href="https://www.cnblogs.com/jiufenshiren" title="https:&#x2F;&#x2F;www.cnblogs.com&#x2F;jiufenshiren" rel="noopener" target="_blank">CnBlogs</a></li><li class="links-of-blogroll-item"><a href="https://home.51cto.com/space?uid=12848310" title="https:&#x2F;&#x2F;home.51cto.com&#x2F;space?uid&#x3D;12848310" rel="noopener" target="_blank">51CTO</a></li></ul></div><script data-embed-id="94f790d6-f7ac-4d04-ad53-55d841525b5a" data-base-api-url="http://124.222.164.140:3001/api/embed" src="http://124.222.164.140:3001/embed/anythingllm-chat-widget.min.js"></script></div></div></div></aside><div class="sidebar-dimmer"></div></header><div class="back-to-top" role="button" aria-label="返回顶部"><i class="fa fa-arrow-up"></i> <span>0%</span></div><a role="button" class="book-mark-link book-mark-link-fixed"></a><noscript><div class="noscript-warning">Theme NexT works best with JavaScript enabled</div></noscript><div class="main-inner index posts-expand"><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/md/linux/linux%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/md/linux/linux%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C/" class="post-title-link" itemprop="url">linux基本操作</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-04-10 21:05:10 21:05:10" itemprop="dateCreated datePublished" datetime="2021-04-10T21:05:10+08:00">2021-04-10 21:05:10</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2021-04-11 20:04:17 20:04:17" itemprop="dateModified" datetime="2021-04-11T20:04:17+08:00">2021-04-11 20:04:17</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-folder"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/hexoblog/categories/linux/" itemprop="url" rel="index"><span itemprop="name">linux</span></a></span></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>126</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>1 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="文件操作"><a href="#文件操作" class="headerlink" title="文件操作"></a>文件操作</h1><h2 id="移动文件-重命名文件"><a href="#移动文件-重命名文件" class="headerlink" title="移动文件/重命名文件"></a>移动文件/重命名文件</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 移动文件</span></span><br><span class="line">mv [源文件目录] [目标文件目录]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 重命名文件</span></span><br><span class="line"><span class="built_in">cd</span> [目标目录]</span><br><span class="line">mv [源文件名] [目标文件名]</span><br></pre></td></tr></table></figure><h2 id="复制文件"><a href="#复制文件" class="headerlink" title="复制文件"></a>复制文件</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cp [源文件目录/源文件名] [目标文件目录]</span><br></pre></td></tr></table></figure><h2 id="删除文件"><a href="#删除文件" class="headerlink" title="删除文件"></a>删除文件</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> [目标文件目录]</span><br><span class="line">rm -rf [目标文件名]</span><br></pre></td></tr></table></figure></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/md/jvm/jvm%E5%91%BD%E4%BB%A4/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/md/jvm/jvm%E5%91%BD%E4%BB%A4/" class="post-title-link" itemprop="url">jvm命令</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-29 20:00:19 20:00:19" itemprop="dateCreated datePublished" datetime="2021-03-29T20:00:19+08:00">2021-03-29 20:00:19</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2021-05-11 16:15:26 16:15:26" itemprop="dateModified" datetime="2021-05-11T16:15:26+08:00">2021-05-11 16:15:26</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-folder"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/hexoblog/categories/jvm/" itemprop="url" rel="index"><span itemprop="name">jvm</span></a></span></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>928</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>1 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="JVM命令的使用"><a href="#JVM命令的使用" class="headerlink" title="JVM命令的使用"></a>JVM命令的使用</h1><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/wangxiaotongfan/article/details/82560739">https://blog.csdn.net/wangxiaotongfan/article/details/82560739</a></p><h2 id="JPS"><a href="#JPS" class="headerlink" title="JPS"></a>JPS</h2><h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>&emsp;&emsp;显示当前系统的java进程。</p><h3 id="格式"><a href="#格式" class="headerlink" title="格式"></a>格式</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"></span><br></pre></td></tr></table></figure><h3 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h3><ol><li>-q：只显示pid，不显示class名称，jar文件名和传递给main方法的参数。</li><li>-l：输出应用程序main class的完整package名或者应用程序的jar文件完整路径名。</li><li>-m：输出jvm启动时传递给main方法启动。</li><li>-v：输出JVM启动时显示指定的JVM参数。</li></ol><h2 id="JSTAT"><a href="#JSTAT" class="headerlink" title="JSTAT"></a>JSTAT</h2><h3 id="介绍-1"><a href="#介绍-1" class="headerlink" title="介绍"></a>介绍</h3><p>&emsp;&emsp;用于监视虚拟机运行时状态信息的命令，它可以显示出虚拟机进程中的类装载、内存、垃圾收集、JIT编译(Just In Time Compiler, 即时编译器)等运行数据。</p><h3 id="格式-1"><a href="#格式-1" class="headerlink" title="格式"></a>格式</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"></span><br></pre></td></tr></table></figure><h3 id="参数-1"><a href="#参数-1" class="headerlink" title="参数"></a>参数</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="string">&quot;<span class="variable">$DEBUG</span>&quot;</span> = <span class="string">&quot;true&quot;</span> ]; <span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> -e <span class="string">&quot;\033[0;31m debug is open,port=<span class="variable">$DEBUG_PORT</span> \033[0m&quot;</span></span><br><span class="line">  JAVA_OPTS=<span class="string">&quot;<span class="variable">$JAVA_OPTS</span> -Xdebug -Xrunjdwp:transport=dt_socket,address=<span class="variable">$DEBUG_PORT</span>,server=y,suspend=y&quot;</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line">JAVA_HEAP_DUMP_OPTS=-XX:HeapDumpPath=<span class="variable">$LOG_HOME</span>/dump.hprof</span><br><span class="line">JAVA_OPTS=<span class="string">&quot;<span class="variable">$JAVA_OPTS</span> -Dserver.port=<span class="variable">$PORT</span> -Dlog.home=<span class="variable">$LOG_HOME</span> -Duse.flume=false -Xms128m -Xmx2048m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=1024m -Dfile.encoding=utf-8 -XX:+HeapDumpOnOutOfMemoryError <span class="variable">$JAVA_HEAP_DUMP_OPTS</span>&quot;</span></span><br><span class="line"><span class="comment">#JAVA_OPTS=&quot;$JAVA_OPTS -XX:+TraceClassLoading -XX:+TraceClassUnloading&quot;</span></span><br></pre></td></tr></table></figure></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/md/java/IO/IO%E6%A8%A1%E5%9E%8B/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/md/java/IO/IO%E6%A8%A1%E5%9E%8B/" class="post-title-link" itemprop="url">IO模型</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-29 19:46:01 19:46:01" itemprop="dateCreated datePublished" datetime="2021-03-29T19:46:01+08:00">2021-03-29 19:46:01</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2021-06-09 10:06:17 10:06:17" itemprop="dateModified" datetime="2021-06-09T10:06:17+08:00">2021-06-09 10:06:17</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-folder"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/hexoblog/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a> </span>， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/hexoblog/categories/java/io/" itemprop="url" rel="index"><span itemprop="name">io</span></a></span></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>1.4k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>1 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h1><p>&emsp;&emsp;IO是输入输出，IO是面向流的。<br>&emsp;&emsp;java中有三种IO模型： BIO，NIO，AIO。它们又可以分为同步异步，阻塞与非阻塞。<br>&emsp;&emsp;而在linux中有5中IO模型。</p><div class="post-button"><a class="btn" href="/hexoblog/md/java/IO/IO%E6%A8%A1%E5%9E%8B/#more" rel="contents">阅读全文 &raquo;</a></div></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/md/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7hash/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/md/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7hash/" class="post-title-link" itemprop="url">一致性hash</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-26 10:49:58 10:49:58" itemprop="dateCreated datePublished" datetime="2021-03-26T10:49:58+08:00">2021-03-26 10:49:58</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2021-05-24 16:48:39 16:48:39" itemprop="dateModified" datetime="2021-05-24T16:48:39+08:00">2021-05-24 16:48:39</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-folder"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/hexoblog/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">分布式</span></a></span></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>719</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>1 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h1><p>&emsp;&emsp;在分布式系统中，通常不同的机器存储着不同的数据，例如redis集群中存储的数据。<br>&emsp;&emsp;这些数据通常采用hash算法来计算出应该存储在那台机器上。但是，当集群中的节点增加或者减少时，通过原有的hash算法计算出来的位置将会完全错误。<br>&emsp;&emsp;一致性hash就是为了解决这种问题诞生的。</p><div class="post-button"><a class="btn" href="/hexoblog/md/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7hash/#more" rel="contents">阅读全文 &raquo;</a></div></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/Spring%20AOP%E5%85%A5%E9%97%A8/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/Spring%20AOP%E5%85%A5%E9%97%A8/" class="post-title-link" itemprop="url">Spring AOP入门</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 11:19:27 11:19:27" itemprop="dateCreated datePublished" datetime="2021-03-15T11:19:27+08:00">2021-03-15 11:19:27</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>11k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>10 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="1、AOP"><a href="#1、AOP" class="headerlink" title="1、AOP"></a>1、AOP</h1><h2 id="1-1、概念"><a href="#1-1、概念" class="headerlink" title="1.1、概念"></a>1.1、概念</h2><p>AOP 为面向切面编程，采用动态代理实现。</p><h2 id="1-2、优点"><a href="#1-2、优点" class="headerlink" title="1.2、优点"></a>1.2、优点</h2><p>采用动态代理的方式，可以增强原有的目标类的方法，我们可以在目标方法执行前后分别做一些事情。<br>对于 aop 就可以在 5 种通知里做一些事情，比如说数据库连接的释放，日志的打印，事务的操作。<br>这种方式，使得不用修改原有程序，就可以增加功能，降低了耦合。</p><h2 id="1-3、结构"><a href="#1-3、结构" class="headerlink" title="1.3、结构"></a>1.3、结构</h2><p><img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/springAOP%E7%BB%93%E6%9E%841.png#id=XfoXj&originHeight=290&originWidth=702&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=XiJ3z&originHeight=290&originWidth=702&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="></p><h1 id="2、AOP-入门案例"><a href="#2、AOP-入门案例" class="headerlink" title="2、AOP 入门案例"></a>2、AOP 入门案例</h1><h2 id="2-1、AOP-前"><a href="#2-1、AOP-前" class="headerlink" title="2.1、AOP 前"></a>2.1、AOP 前</h2><p>AOP 采用动态代理实现，故很有必要在看 AOP 前先看动态代理的实现。动态代理分为两种，对于有接口，有实现类的可以采用 jdk 动态代理，对于没有接口，只有实现类的，需要采用 cglib 代理。</p><h3 id="2-1-1、依赖包"><a href="#2-1-1、依赖包" class="headerlink" title="2.1.1、依赖包"></a>2.1.1、依赖包</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>spring-core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>spring-beans<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>spring-expression<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>spring-aop<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.aopalliance<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>com.springsource.org.aopalliance<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.aspectj<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>aspectjweaver<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.6.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><h2 id="2-2、jdk-动态代理-AOP-手动方式"><a href="#2-2、jdk-动态代理-AOP-手动方式" class="headerlink" title="2.2、jdk 动态代理(AOP 手动方式)"></a>2.2、jdk 动态代理(AOP 手动方式)</h2><p>jdk 动态代理中，代理类需要实现目标类的所有接口。</p><h3 id="2-2-1、目标类：接口-实现类"><a href="#2-2-1、目标类：接口-实现类" class="headerlink" title="2.2.1、目标类：接口+实现类"></a>2.2.1、目标类：接口+实现类</h3><p>接口：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addUser</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateUser</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteUser</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>实现类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;addUser&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;updateUser&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;deleteUser&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-2-2、切面类：用于保存通知"><a href="#2-2-2、切面类：用于保存通知" class="headerlink" title="2.2.2、切面类：用于保存通知"></a>2.2.2、切面类：用于保存通知</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAspect</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;brfore&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">after</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;after&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-2-3、代理类：生成代理对象"><a href="#2-2-3、代理类：生成代理对象" class="headerlink" title="2.2.3、代理类：生成代理对象"></a>2.2.3、代理类：生成代理对象</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanFactory</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> UserService <span class="title">createService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1、目标类</span></span><br><span class="line">        <span class="keyword">final</span> UserService userService = <span class="keyword">new</span> UserServiceImpl();</span><br><span class="line">        <span class="comment">// 2、切面类</span></span><br><span class="line">        <span class="keyword">final</span> MyAspect myAspect = <span class="keyword">new</span> MyAspect();</span><br><span class="line">        <span class="comment">// 3、代理对象</span></span><br><span class="line">        <span class="comment">// 参数1、类加载器</span></span><br><span class="line">                         当前类.class.getClassLoader()</span><br><span class="line">                        目标类对象.getClass().getClassLoader()</span><br><span class="line">        <span class="comment">// 参数2、目标类所实现的所有接口</span></span><br><span class="line">                        目标类对象.getClass().getInterfaces()</span><br><span class="line">                        <span class="keyword">new</span> Class[]&#123;接口.class&#125;</span><br><span class="line">        <span class="comment">// 参数3、InvocationHandler处理类，采用匿名内部类实现</span></span><br><span class="line">        UserService proxyService = (UserService) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(),</span><br><span class="line">        userService.getClass().getInterfaces(), <span class="keyword">new</span> InvocationHandler() &#123;</span><br><span class="line">            <span class="comment">//参数1proxy、代理对象</span></span><br><span class="line">            <span class="comment">//参数2method、要执行方法的描述对象</span></span><br><span class="line">            <span class="comment">//参数3arg2、方法的实际参数</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] arg2)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">                myAspect.before();</span><br><span class="line">                Object obj = method.invoke(userService, arg2);</span><br><span class="line">                myAspect.after();</span><br><span class="line">                <span class="keyword">return</span> obj;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> proxyService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-2-4、测试类："><a href="#2-2-4、测试类：" class="headerlink" title="2.2.4、测试类："></a>2.2.4、测试类：</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    UserService userService = MyBeanFactory.createService();</span><br><span class="line">    userService.addUser();</span><br><span class="line">    userService.updateUser();</span><br><span class="line">    userService.deleteUser();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="2-3、cglib-代理放式"><a href="#2-3、cglib-代理放式" class="headerlink" title="2.3、cglib 代理放式"></a>2.3、cglib 代理放式</h2><p>cglib 代理适用于没有接口只有实现类的情况。cglib 是通过让代理类继承目标类，从而增强目标类的方法。</p><h3 id="2-3-1、目标类等同于-jdk-动态代理的接口的实现类"><a href="#2-3-1、目标类等同于-jdk-动态代理的接口的实现类" class="headerlink" title="2.3.1、目标类等同于 jdk 动态代理的接口的实现类"></a>2.3.1、目标类等同于 jdk 动态代理的接口的实现类</h3><h3 id="2-3-2、切面类同上"><a href="#2-3-2、切面类同上" class="headerlink" title="2.3.2、切面类同上"></a>2.3.2、切面类同上</h3><h3 id="2-3-3、测试类同上"><a href="#2-3-3、测试类同上" class="headerlink" title="2.3.3、测试类同上"></a>2.3.3、测试类同上</h3><h3 id="2-3-4、代理类"><a href="#2-3-4、代理类" class="headerlink" title="2.3.4、代理类"></a>2.3.4、代理类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanFactory</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> UserServiceImpl <span class="title">createService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 1、目标类</span></span><br><span class="line">    <span class="keyword">final</span> UserServiceImpl userService = <span class="keyword">new</span> UserServiceImpl();</span><br><span class="line">    <span class="comment">// 2、切面类</span></span><br><span class="line">    <span class="keyword">final</span> MyAspect myAspect = <span class="keyword">new</span> MyAspect();</span><br><span class="line">    <span class="comment">// 3、代理类</span></span><br><span class="line">    Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line">    <span class="comment">//设置父类</span></span><br><span class="line">    enhancer.setSuperclass(userService.getClass());</span><br><span class="line">    <span class="comment">/* 设置回调函数 , MethodInterceptor接口 等效 jdk中 InvocationHandler接口</span></span><br><span class="line"><span class="comment">     * intercept() 等效 jdk invoke()</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    enhancer.setCallback(<span class="keyword">new</span> MethodInterceptor() &#123;</span><br><span class="line">        <span class="comment">//参数1、代理对象</span></span><br><span class="line">        <span class="comment">//参数2、要执行方法的描述对象(当前)</span></span><br><span class="line">        <span class="comment">//参数3、方法的实际参数</span></span><br><span class="line">        <span class="comment">//参数4、代理类方法的代理</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            myAspect.before();</span><br><span class="line">            <span class="comment">//通过反射的方式执行要目标类的方法</span></span><br><span class="line">            Object obj = arg1.invoke(userService, arg2);</span><br><span class="line">            <span class="comment">//执行代理类的父类（目标类）</span></span><br><span class="line">            arg3.invokeSuper(arg0, arg2);</span><br><span class="line">            myAspect.after();</span><br><span class="line">            <span class="keyword">return</span> obj;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">//创建代理对象，向上转型</span></span><br><span class="line">    UserServiceImpl proxyService = (UserServiceImpl) enhancer.create();</span><br><span class="line">    <span class="keyword">return</span> proxyService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="2-4、AOP-半自动代理"><a href="#2-4、AOP-半自动代理" class="headerlink" title="2.4、AOP 半自动代理"></a>2.4、AOP 半自动代理</h2><p>半自动代理采用 spring 提供的 org.springframework.aop.framework.ProxyFactoryBean 类（一个代理工厂）生成代理对象</p><h3 id="2-4-1、目标类与-jdk-动态代理相同"><a href="#2-4-1、目标类与-jdk-动态代理相同" class="headerlink" title="2.4.1、目标类与 jdk 动态代理相同"></a>2.4.1、目标类与 jdk 动态代理相同</h3><h3 id="2-4-2、切面类：环绕通知（此处与其他不同）"><a href="#2-4-2、切面类：环绕通知（此处与其他不同）" class="headerlink" title="2.4.2、切面类：环绕通知（此处与其他不同）"></a>2.4.2、切面类：环绕通知（此处与其他不同）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAspect</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span></span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">Object</span> <span class="title">invoke</span>(<span class="title">MethodInvocation</span> <span class="title">arg0</span>) <span class="title">throws</span> <span class="title">Throwable</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;before&quot;</span>);</span><br><span class="line">        Object obj = arg0.proceed();</span><br><span class="line">        System.out.println(<span class="string">&quot;after&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> obj;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-4-3、配置文件-beans-xml"><a href="#2-4-3、配置文件-beans-xml" class="headerlink" title="2.4.3、配置文件 beans.xml"></a>2.4.3、配置文件 beans.xml</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">             <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">             <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                                                http://www.springframework.org/schema/beans/spring-beans.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 目标类 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;beanfactory.UserServiceImpl&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 切面类 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;myAspect&quot;</span> <span class="attr">class</span>=<span class="string">&quot;beanfactory.MyAspect&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 代理类 --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 使用spring提供的代理工厂 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;proxyService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 目标类的接口 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;interfaces&quot;</span> <span class="attr">value</span>=<span class="string">&quot;beanfactory.UserService&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 目标类 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;target&quot;</span> <span class="attr">ref</span>=<span class="string">&quot;userService&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 只能放一个切面类 --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 切面类的名称 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;interceptorNames&quot;</span> <span class="attr">value</span>=<span class="string">&quot;myAspect&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="2-4-4、测试类"><a href="#2-4-4、测试类" class="headerlink" title="2.4.4、测试类"></a>2.4.4、测试类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fun</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    String xmlPath = <span class="string">&quot;beanfactory/beans.xml&quot;</span>;</span><br><span class="line">    ApplicationContext applicationContext = <span class="keyword">new</span> ClassPathXmlApplicationContext(xmlPath);</span><br><span class="line">    <span class="comment">// 获得代理对象</span></span><br><span class="line">    UserService userService = (UserService) applicationContext.getBean(<span class="string">&quot;proxyService&quot;</span>);</span><br><span class="line">    userService.addUser();</span><br><span class="line">    userService.updateUser();</span><br><span class="line">    userService.deleteUser();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>2.4.5、结果<br>before<br>addUser<br>after<br>before<br>updateUser<br>after<br>before<br>deleteUser<br>after</p><h2 id="2-5、AOP-全自动代理"><a href="#2-5、AOP-全自动代理" class="headerlink" title="2.5、AOP 全自动代理"></a>2.5、AOP 全自动代理</h2><p>全自动代理仅需要在 beans.xml 中配置一下就好，使用<a href="aop:config">aop:config</a>。<br>spring 会自动判断使用那种代理方式，有接口时采用 jdk 方式，没有接口时采用 cglib 方式。</p><h3 id="2-5-1、目标类与-jdk-动态代理相同"><a href="#2-5-1、目标类与-jdk-动态代理相同" class="headerlink" title="2.5.1、目标类与 jdk 动态代理相同"></a>2.5.1、目标类与 jdk 动态代理相同</h3><h3 id="2-5-2、测试类与半自动方式相同"><a href="#2-5-2、测试类与半自动方式相同" class="headerlink" title="2.5.2、测试类与半自动方式相同"></a>2.5.2、测试类与半自动方式相同</h3><h3 id="2-5-3、切面类"><a href="#2-5-3、切面类" class="headerlink" title="2.5.3、切面类"></a>2.5.3、切面类</h3><p>AOP 提供了 5 中通知类型，分别为，前置通知，返回通知，异常通知，最终通知，环绕通知，其中环绕通知最为强大。<br>除环绕通知，其他可以没有参数。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAspect</span> </span>&#123;</span><br><span class="line">    <span class="comment">//前置通知，在目标类方法执行前执行</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">(JoinPoint joinPoint)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;before&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//返回通知，在目标类方法执行后执行，可以拿到目标类方法的返回值，如果没有就是null</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterreturning</span><span class="params">(JoinPoint joinPoint, Object ret)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;afterreturning&quot;</span> + ret);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//异常通知，当目标类方法抛出异常时执行，可以拿到异常信息，类似于在catch块里面的方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">throwable</span><span class="params">(JoinPoint joinPoint, Throwable e)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;throwable&quot;</span> + <span class="string">&quot; &quot;</span> + e.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//在最后执行</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterafter</span><span class="params">(JoinPoint joinPoint)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;afterafter&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//在方法前后都会执行</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(ProceedingJoinPoint jontPoint)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;环绕通知--------&gt;前&quot;</span>);</span><br><span class="line">        Object obj = jontPoint.proceed();</span><br><span class="line">        System.out.println(<span class="string">&quot;环绕通知----------&gt;后&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> obj;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-5-4、配置文件-beans-xml"><a href="#2-5-4、配置文件-beans-xml" class="headerlink" title="2.5.4、配置文件 beans.xml"></a>2.5.4、配置文件 beans.xml</h3><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span><br><span class="line">             xmlns:xsi=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="line">             xmlns:aop=<span class="string">&quot;http://www.springframework.org/schema/aop&quot;</span></span><br><span class="line">             xsi:schemaLocation=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span><br><span class="line"><span class="string">                                                http://www.springframework.org/schema/beans/spring-beans.xsd</span></span><br><span class="line"><span class="string">                                                http://www.springframework.org/schema/aop</span></span><br><span class="line"><span class="string">                                                http://www.springframework.org/schema/aop/spring-aop.xsd&quot;</span>&gt;</span><br><span class="line">    &lt;!-- 目标类 --&gt;</span><br><span class="line">    &lt;bean id=&quot;userService&quot; class=&quot;aop.UserServiceImpl&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;!-- 切面类 --&gt;</span><br><span class="line">    &lt;bean id=&quot;myAspect&quot; class=&quot;aop.MyAspect&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;!-- proxs-target-<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;true&quot;</span>：强制采用cglib方式代理 --&gt;</span><br><span class="line">    &lt;aop:config proxy-target-<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;true&quot;</span>&gt;</span><br><span class="line">        &lt;!-- 切入点 --&gt;</span><br><span class="line">        &lt;aop:pointcut expression=<span class="string">&quot;execution(* aop.UserService.*(..))&quot;</span> id=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">        &lt;!-- 切面 --&gt;</span><br><span class="line">        &lt;aop:aspect ref=<span class="string">&quot;myAspect&quot;</span>&gt;</span><br><span class="line">            &lt;!-- 前置通知 --&gt;</span><br><span class="line">            &lt;aop:before method=<span class="string">&quot;before&quot;</span> pointcut-ref=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">            &lt;!-- 返回通知 --&gt;</span><br><span class="line">            &lt;aop:after-returning method=<span class="string">&quot;afterreturning&quot;</span> returning=<span class="string">&quot;ret&quot;</span> pointcut-ref=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">            &lt;!-- 环绕通知 --&gt;</span><br><span class="line">            &lt;aop:around method=<span class="string">&quot;invoke&quot;</span> pointcut-ref=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">            &lt;!-- 异常通知 --&gt;</span><br><span class="line">            &lt;aop:after-throwing method=<span class="string">&quot;throwable&quot;</span> throwing=<span class="string">&quot;e&quot;</span> pointcut-ref=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">            &lt;!-- 最终通知 --&gt;</span><br><span class="line">            &lt;aop:after method=<span class="string">&quot;afterafter&quot;</span> pointcut-ref=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span><br><span class="line">        &lt;/aop:aspect&gt;</span><br><span class="line">    &lt;/aop:config&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure><h3 id="2-5-5、结果"><a href="#2-5-5、结果" class="headerlink" title="2.5.5、结果"></a>2.5.5、结果</h3><p>因为环绕通知中有 return 语句，故执行顺序和配置有关。</p><h4 id="2-5-5-1、配置环绕通知时"><a href="#2-5-5-1、配置环绕通知时" class="headerlink" title="2.5.5.1、配置环绕通知时"></a>2.5.5.1、配置环绕通知时</h4><p>before 环绕通知——–&gt;前 addUser<br>afterafter 环绕通知———-&gt;后 afterreturning1</p><hr><p>before 环绕通知——–&gt;前 deleteUser<br>afterafter 环绕通知———-&gt;后 afterreturningnull</p><hr><p>before 环绕通知——–&gt;前 updateUser<br>afterafter<br>throwable / by zero</p><h4 id="2-5-5-2、不配置环绕通知"><a href="#2-5-5-2、不配置环绕通知" class="headerlink" title="2.5.5.2、不配置环绕通知"></a>2.5.5.2、不配置环绕通知</h4><p>before<br>addUser<br>afterreturning1<br>afterafter</p><hr><p>before<br>deleteUser<br>afterreturningnull<br>afterafter</p><hr><p>before<br>updateUser<br>throwable / by zero<br>afterafter</p><h4 id="2-5-5-3、其他"><a href="#2-5-5-3、其他" class="headerlink" title="2.5.5.3、其他"></a>2.5.5.3、其他</h4><p>异常通知，只有在产生异常后才会执行，此时，返回通知会被异常挡住不在执行。<br>返回通知可以拿到目标类方法拿到的返回值，如果没有返回值，就是 null。<br>环绕通知会使得最终通知提前。类似于，return 执行前，finally 块中的会先执行。</p><h3 id="2-5-6、补充"><a href="#2-5-6、补充" class="headerlink" title="2.5.6、补充"></a>2.5.6、补充</h3><p>全自动方式也可将切面做成类似于半自动的形式。<br>切面类：<br>前置通知：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAspectBefore</span> <span class="keyword">implements</span> <span class="title">MethodBeforeAdvice</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">(Method arg0, Object[] arg1, Object arg2)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;before&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>环绕通知：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAspectMethod</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation arg0)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;环绕前&quot;</span>);</span><br><span class="line">        Object obj = arg0.proceed();</span><br><span class="line">        System.out.println(<span class="string">&quot;环绕后&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> obj;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>配置方式：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">aop:config</span> <span class="attr">proxy-target-class</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 切入点 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:pointcut</span> <span class="attr">expression</span>=<span class="string">&quot;execution(* aop2.UserService.*(..))&quot;</span> <span class="attr">id</span>=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 特殊的切面,只有一个环绕通知 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:advisor</span> <span class="attr">advice-ref</span>=<span class="string">&quot;myAspectMethod&quot;</span> <span class="attr">pointcut-ref</span>=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:advisor</span> <span class="attr">advice-ref</span>=<span class="string">&quot;myAspectBefore&quot;</span> <span class="attr">pointcut-ref</span>=<span class="string">&quot;myPointCut&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">aop:config</span>&gt;</span></span><br></pre></td></tr></table></figure></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/%E9%9B%86%E5%90%88%E6%95%B4%E7%90%86%E5%8F%8A%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/%E9%9B%86%E5%90%88%E6%95%B4%E7%90%86%E5%8F%8A%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C/" class="post-title-link" itemprop="url">集合整理及基础操作</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 10:58:38 10:58:38" itemprop="dateCreated datePublished" datetime="2021-03-15T10:58:38+08:00">2021-03-15 10:58:38</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>4.3k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>4 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="集合整理及基础操作"><a href="#集合整理及基础操作" class="headerlink" title="集合整理及基础操作"></a>集合整理及基础操作</h1><h1 id="1、接口关系整理"><a href="#1、接口关系整理" class="headerlink" title="1、接口关系整理"></a>1、接口关系整理</h1><p>集合顶层分为两大接口，collection，map<br>collection：单列元素集合的顶层接口。list 与 set 接口继承 collection 接口。<br>map：双列元素集合的顶层接口。<br>由此形成集合的三大类型。list、set、map。<img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/%E9%9B%86%E5%90%88%E6%8E%A5%E5%8F%A3%E7%BB%A7%E6%89%BF%E5%9B%BE1.png#id=fn5GQ&originHeight=453&originWidth=702&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=DvcOD&originHeight=453&originWidth=702&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="><br>Queen，使用较少，暂时不说有时间补上。</p><h1 id="2、map-介绍"><a href="#2、map-介绍" class="headerlink" title="2、map 介绍"></a>2、map 介绍</h1><p>map 作为双列集合的跟接口，以键值对的形式存放元素。<br>java 中不提供对 map 接口的直接实现。使用其实现类构造对象。<br>主要使用的实现类有 HashMap 和 TreeMap。</p><h2 id="2-1、HashMap"><a href="#2-1、HashMap" class="headerlink" title="2.1、HashMap"></a>2.1、HashMap</h2><h3 id="2-1-1、增删等操作"><a href="#2-1-1、增删等操作" class="headerlink" title="2.1.1、增删等操作"></a>2.1.1、增删等操作</h3><p>使用 put()，putAll()方法增加数据。put 方法将一个个键值对存放入 map 中，而 putAll 则将另一个集合添加进当前集合中。<br>putAll()方法添加的是集合的元素，会将一个集合中的元素添加到另一个集合中。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Map m = <span class="keyword">new</span> HashMap();m.put(<span class="string">&quot;1&quot;</span>, <span class="string">&quot;1&quot;</span>);</span><br><span class="line">m.put(<span class="string">&quot;2&quot;</span>, <span class="string">&quot;2&quot;</span>);</span><br><span class="line">m.put(<span class="string">&quot;3&quot;</span>, <span class="string">&quot;3&quot;</span>);</span><br><span class="line">m.put(<span class="string">&quot;4&quot;</span>, <span class="string">&quot;4&quot;</span>);</span><br><span class="line">Map m1 = <span class="keyword">new</span> HashMap();</span><br><span class="line">m1.put(<span class="string">&quot;a&quot;</span>,<span class="string">&quot;a&quot;</span>);</span><br><span class="line">m.putAll(m1);</span><br></pre></td></tr></table></figure><p>使用 get()方法可以根据指定的键获相应的值。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Object o = m.get(<span class="string">&quot;1&quot;</span>);</span><br></pre></td></tr></table></figure><p>clear()方法则可以清空 map 集合中的数据。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m.clear();</span><br></pre></td></tr></table></figure><p>使用 contansKey()和 cotainsValue()则可以分别根据 key 和 value 判断集合中是否包含该元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> b = m.containsKey(<span class="string">&quot;1&quot;</span>);<span class="keyword">boolean</span> b1 = m.containsValue(<span class="string">&quot;1&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 keySet()可以获取该 map 中所有 key 的集合。将其放入一个 set 集合中。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Set keyset = m.keySet();</span><br></pre></td></tr></table></figure><p>使用 value()方法可以获取 map 中所有的值。不存在键值关系。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Collection values = m.values();</span><br></pre></td></tr></table></figure><p>返回此映射中包含的映射关系的  Set  视图。不好理解，迭代时会用到。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Set entryset = m.entrySet();</span><br></pre></td></tr></table></figure><h3 id="2-1-2、源码和原理"><a href="#2-1-2、源码和原理" class="headerlink" title="2.1.2、源码和原理"></a>2.1.2、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/gm59x0?view=doc_embed">HashMap 原理与源码解析</a></p><h2 id="2-2、TreeMap"><a href="#2-2、TreeMap" class="headerlink" title="2.2、TreeMap"></a>2.2、TreeMap</h2><h3 id="2-2-1、treemap-与-hashmap-的区别"><a href="#2-2-1、treemap-与-hashmap-的区别" class="headerlink" title="2.2.1、treemap 与 hashmap 的区别"></a>2.2.1、treemap 与 hashmap 的区别</h3><p>treemap 追溯源头，treemap 不仅实现了 map 接口，也是实现了，sortedmap 接口。treemap 是有序的而 hashmap 无序。<br>treemap 是红黑树基于 sortedmap 接口的实现。而 hashmap 则根据键的 hashcode 存放数据。</p><h3 id="2-2-2、增删等操作"><a href="#2-2-2、增删等操作" class="headerlink" title="2.2.2、增删等操作"></a>2.2.2、增删等操作</h3><p>因为实现了 map 接口，普通基础操作与 hashmap 相同。只是多了从 sortedmap 实现得来的排序能力。<br>插入 treemap 的键必须是可以比较的，即实现了 Comparable 接口，否则会抛出异常。<br>插入的键为自定义对象时需要实现 Comparable 接口，重写其中的方法。<br>同样可以自定义 treemap 的排序规则。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer,Integer&gt; m2 = <span class="keyword">new</span> TreeMap(<span class="keyword">new</span> Comparator() &#123;    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Object o1, Object o2)</span> </span>&#123;</span><br><span class="line">        Double a = (Double) o1;</span><br><span class="line">        Double b = (Double) o2;</span><br><span class="line">        <span class="keyword">return</span> (a &gt; b ? <span class="number">1</span> : <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><h3 id="2-2-3、源码和原理"><a href="#2-2-3、源码和原理" class="headerlink" title="2.2.3、源码和原理"></a>2.2.3、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/aec1vz?view=doc_embed">TreeMap 原理与源码解析</a></p><h1 id="3、list-介绍"><a href="#3、list-介绍" class="headerlink" title="3、list 介绍"></a>3、list 介绍</h1><p>list 继承了 collection 接口，是 ArrayList，LinkedList 等 List 集合的跟接口。list 集合是单列集合。<br>因为 list 底层采用链表或数组实现，所以 list 是一种无序的集合。</p><h2 id="3-1、ArrayList"><a href="#3-1、ArrayList" class="headerlink" title="3.1、ArrayList"></a>3.1、ArrayList</h2><h3 id="3-1-1、增删改等操作"><a href="#3-1-1、增删改等操作" class="headerlink" title="3.1.1、增删改等操作"></a>3.1.1、增删改等操作</h3><p>采用 add()方法添加元素添加为 list 的最后一个元素，也可以将元素添加到指定位置。添加指定位置时，按照索引地址添加，从 0 开始。<br>采用 addAll()方法可以将另一个集合（实现了 Collection）整体添加进来。也可以添加到指定位置。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">List l1 = <span class="keyword">new</span> ArrayList();</span><br><span class="line">l1.add(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">l1.add(<span class="number">1</span>,<span class="string">&quot;2&quot;</span>);</span><br><span class="line">l1.add(<span class="string">&quot;3&quot;</span>);</span><br><span class="line">l1.add(<span class="string">&quot;4&quot;</span>);</span><br><span class="line">List l2 = <span class="keyword">new</span> ArrayList();</span><br><span class="line">l2.add(<span class="string">&quot;5&quot;</span>);</span><br><span class="line">l2.add(<span class="string">&quot;6&quot;</span>);</span><br><span class="line">List l3 = <span class="keyword">new</span> ArrayList();</span><br><span class="line">l3.add(<span class="string">&quot;7&quot;</span>);</span><br><span class="line">l3.add(<span class="string">&quot;8&quot;</span>);</span><br><span class="line">l1.addAll(l2);</span><br><span class="line">l1.addAll(<span class="number">1</span>,l3);</span><br></pre></td></tr></table></figure><p>使用 get()方法根据元素的下标获取元素的值。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Object o = l1.get(<span class="number">1</span>);</span><br></pre></td></tr></table></figure><p>使用 clear()方法可以清楚集合中的元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">l1.clear();</span><br></pre></td></tr></table></figure><p>contains()方法和 containsAll()方法用于判断该集合中是否包含指定的元素，或集合。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> contains = l1.contains(<span class="string">&quot;1&quot;</span>);</span><br><span class="line"><span class="keyword">boolean</span> b = l1.containsAll(l3);</span><br></pre></td></tr></table></figure><p>isEmpty()方法用于判断该集合是否为空。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> empty = l1.isEmpty();</span><br></pre></td></tr></table></figure><p>使用 remove()方法可以移除集合中的元素，可以直接移除也可以根据索引移除。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">l1.remove(<span class="number">3</span>);</span><br><span class="line">l1.remove(<span class="string">&quot;7&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 set()方法可以为集合中指定位置的元素设置值。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">l1.set(<span class="number">1</span>,<span class="string">&quot;a&quot;</span>);</span><br></pre></td></tr></table></figure><p>list 虽然无序，但是可以使用 sort()方法对其排序，需要传入自定义的比较器。会按照比较器规则排序。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">l1.sort(<span class="keyword">new</span> Comparator() &#123;    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Object o1, Object o2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><h3 id="3-1-2、源码和原理"><a href="#3-1-2、源码和原理" class="headerlink" title="3.1.2、源码和原理"></a>3.1.2、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/rybeyb?view=doc_embed">ArrayList 原理与源码解析</a></p><h2 id="3-2、LinkedList"><a href="#3-2、LinkedList" class="headerlink" title="3.2、LinkedList"></a>3.2、LinkedList</h2><h3 id="3-2-1、与-ArrayList-区别"><a href="#3-2-1、与-ArrayList-区别" class="headerlink" title="3.2.1、与 ArrayList 区别"></a>3.2.1、与 ArrayList 区别</h3><p>1、ArrayList 是实现了基于动态数组的数据结构，LinkedList 基于链表的数据结构。<br>2、对于随机访问 get 和 set，ArrayList 觉得优于 LinkedList，因为 LinkedList 要移动指针。 3.、对于新增和删除操作 add 和 remove，LinedList 比较占优势，因为 ArrayList 要移动数。</p><h3 id="3-2-2、增删改等操作"><a href="#3-2-2、增删改等操作" class="headerlink" title="3.2.2、增删改等操作"></a>3.2.2、增删改等操作</h3><p>普通基础操作与 ArrayList 基本相同，只是实现原理不同。<br>LinkedList 与 ArrayList 相比，多了一部分在链表头和尾操作的方法。<br>增加了增加，获取，移除的方法。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">l1.addFirst(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">l1.addLast(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">l1.removeFirst();</span><br><span class="line">l1.removeLast();</span><br><span class="line">l1.getFirst();</span><br><span class="line">l1.getLast();</span><br></pre></td></tr></table></figure><p>使用 offer()，offerLast()，offerFirst()方法，添加元素，可以获取返回值绝对为 true。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">l1.offer(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">l1.offerFirst(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">l1.offerLast(<span class="string">&quot;3&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 peek()，peekLast()，peekFirst()获取元素头节点尾节点的值，不会移除节点。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Object peek = l1.peek();</span><br><span class="line">Object o1 = l1.peekFirst();</span><br><span class="line">Object o = l1.peekLast();</span><br></pre></td></tr></table></figure><p>使用 poll()，pollLast()，pollFirst()获取元素头节点尾节点的值，会移除节点。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Object poll = l1.poll();</span><br><span class="line">Object o2 = l1.pollFirst();</span><br><span class="line">Object o3 = l1.pollLast();</span><br></pre></td></tr></table></figure><h3 id="3-2-3、源码和原理"><a href="#3-2-3、源码和原理" class="headerlink" title="3.2.3、源码和原理"></a>3.2.3、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/df9mzg?view=doc_embed">LinkedList 原理与源码解析</a></p><h1 id="4、Set-介绍"><a href="#4、Set-介绍" class="headerlink" title="4、Set 介绍"></a>4、Set 介绍</h1><h2 id="4-1、HashSet"><a href="#4-1、HashSet" class="headerlink" title="4.1、HashSet"></a>4.1、HashSet</h2><h3 id="4-1-1、增删改等操作"><a href="#4-1-1、增删改等操作" class="headerlink" title="4.1.1、增删改等操作"></a>4.1.1、增删改等操作</h3><p>使用 add()方法添加元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">HashSet set = <span class="keyword">new</span> HashSet();set.add(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">set.add(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">set.add(<span class="string">&quot;3&quot;</span>);</span><br><span class="line">set.add(<span class="string">&quot;4&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 contains()方法判断集合中是否存在该元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> contains = set.contains(<span class="string">&quot;1&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 remove()方法移除集合中的该元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> remove = set.remove(<span class="string">&quot;1&quot;</span>);</span><br></pre></td></tr></table></figure><p>使用 isEmpty()方法判断集合元素是否为空。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">boolean</span> empty = set.isEmpty();</span><br></pre></td></tr></table></figure><p>使用 size()方法获取集合元素个数。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> size = set.size();</span><br></pre></td></tr></table></figure><p>使用 clear()方法清空集合中的元素。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">set.clear();</span><br></pre></td></tr></table></figure><h3 id="4-1-2、源码和原理"><a href="#4-1-2、源码和原理" class="headerlink" title="4.1.2、源码和原理"></a>4.1.2、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/abfbxv?view=doc_embed">HashSet 原理与源码分析</a></p><h2 id="4-2、TreeSet"><a href="#4-2、TreeSet" class="headerlink" title="4.2、TreeSet"></a>4.2、TreeSet</h2><h3 id="4-2-1、与-HashSet-区别"><a href="#4-2-1、与-HashSet-区别" class="headerlink" title="4.2.1、与 HashSet 区别"></a>4.2.1、与 HashSet 区别</h3><p>与 HashSet 相似，TreeSet 底层同样采用 TreeMap 实现。同样具备 HashSet 不具备的排序能力。<br>底层使用 TreeMap 存放 key 的一列，而基于红黑树实现。</p><h3 id="4-2-2、增删改等操作"><a href="#4-2-2、增删改等操作" class="headerlink" title="4.2.2、增删改等操作"></a>4.2.2、增删改等操作</h3><p>TreeSet 实现了与 HashSet 相同的 Set 接口，其基础操作相同。<br>因为其具备排序能力，所以在 TreeSet 存储自定义对象时，自定义对象需要实现 Comparator 接口，重写其中的方法。<br>需要自定义排序规则。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">TreeSet t = <span class="keyword">new</span> TreeSet(<span class="keyword">new</span> Comparator() &#123;</span><br><span class="line">    <span class="meta">@Override</span>    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Object o1, Object o2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><h3 id="4-2-3、源码和原理"><a href="#4-2-3、源码和原理" class="headerlink" title="4.2.3、源码和原理"></a>4.2.3、源码和原理</h3><p><a target="_blank" rel="noopener" href="https://www.yuque.com/jiufenshiren/acarw0/lppcbr?view=doc_embed">TreeSet 原理与源码分析</a></p></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/%E9%9B%86%E5%90%88%E5%B9%B6%E5%8F%91%E4%BF%AE%E6%94%B9%E5%BC%82%E5%B8%B8/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/%E9%9B%86%E5%90%88%E5%B9%B6%E5%8F%91%E4%BF%AE%E6%94%B9%E5%BC%82%E5%B8%B8/" class="post-title-link" itemprop="url">集合并发修改异常</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 10:58:03 10:58:03" itemprop="dateCreated datePublished" datetime="2021-03-15T10:58:03+08:00">2021-03-15 10:58:03</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>3k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>3 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="集合并发修改异常"><a href="#集合并发修改异常" class="headerlink" title="集合并发修改异常"></a>集合并发修改异常</h1><p>先看例子<img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/concurrentMOdified1.png#id=YBqYb&originHeight=501&originWidth=554&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=AUfJ7&originHeight=501&originWidth=554&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="><br>在对集合进行迭代器遍历时，在遍历过程中对集合中元素进行增加或删除，在删除数据之后会报并发修改异常。</p><h2 id="原因："><a href="#原因：" class="headerlink" title="原因："></a>原因：</h2><p>在迭代过程中，不能修改集合结构。<br>我们采用 hasnext()方法判断集合是否还有元素可遍历，采用 next()方法获取元素。而 next()方法会每次检查集合结构是否发生变化。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    checkForComodification();</span><br><span class="line">    <span class="keyword">int</span> i = cursor;</span><br><span class="line">    <span class="keyword">if</span> (i &gt;= size)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">    Object[] elementData = ArrayList.<span class="keyword">this</span>.elementData;</span><br><span class="line">    <span class="keyword">if</span> (i &gt;= elementData.length)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    cursor = i + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> (E) elementData[lastRet = i];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>next()方法会在第一行调用 checkForComodification()方法检测集合结构是否发生变化。如果发生变化则会报异常。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">checkForComodification</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>checkForComodification()方法会检查集合结构是否发生变化。<br>cursor 是下一次要取的元素下标，next()方法执行后，cursor 就会往后移动一下。<br>这里<strong>modCount</strong>是 ArrayList 继承自 AbstractList 的变量，用来记录集合元素个数发生变化（增加和删除）的次数。<br><strong>expectedModCount</strong>是类 Itr 的变量，是迭代器记录集合元素个数变化的次数。如下图所示：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Iterator&lt;E&gt; <span class="title">iterator</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Itr();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * An optimized version of AbstractList.Itr</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Itr</span> <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> cursor;       <span class="comment">// index of next element to return</span></span><br><span class="line">    <span class="keyword">int</span> lastRet = -<span class="number">1</span>; <span class="comment">// index of last element returned; -1 if no such</span></span><br><span class="line">    <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    Itr() &#123;&#125;</span><br></pre></td></tr></table></figure><p>在调用 iterator()方法时会返回一个 Itr 类的对象，同时会创建变量 expectedModCount，并将 modCount 传递给它，此时这两个值相等。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">remove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">	rangeCheck(index);</span><br><span class="line">	modCount++;</span><br><span class="line">	E oldValue = elementData(index);</span><br><span class="line">	<span class="keyword">int</span> numMoved = size - index - <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">		System.arraycopy(elementData, index+<span class="number">1</span>, elementData, index,</span><br><span class="line">					 numMoved);</span><br><span class="line">	elementData[--size] = <span class="keyword">null</span>; <span class="comment">// clear to let GC do its work</span></span><br><span class="line">	<span class="keyword">return</span> oldValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">	ensureCapacityInternal(size + <span class="number">1</span>);  <span class="comment">// Increments modCount!!</span></span><br><span class="line">	elementData[size++] = e;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ensureCapacityInternal</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">	ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ensureExplicitCapacity</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">	modCount++;</span><br><span class="line">	<span class="comment">// overflow-conscious code</span></span><br><span class="line">	<span class="keyword">if</span> (minCapacity - elementData.length &gt; <span class="number">0</span>)</span><br><span class="line">		grow(minCapacity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>而我们在对集合中添加或删除元素时，都会改变 modCount 的值，如上图所示：<br>当添加或删除这个操作在迭代过程中时，next()方法检查到 modCount 与 expectedModCount 值不一样，就会报并发修改异常。<br>那为什么迭代器自己的方法不会报异常？如下所示：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">	checkForComodification();</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		ArrayList.<span class="keyword">this</span>.remove(lastRet);</span><br><span class="line">		cursor = lastRet;</span><br><span class="line">		lastRet = -<span class="number">1</span>;</span><br><span class="line">		expectedModCount = modCount;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (IndexOutOfBoundsException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>我们发现迭代器自己的 remove()方法底层还是调用集合的 remove()方法，但比集合的 remove()方法多了一个在删除过后修改 expectedModCount 变量的过程。<br>使得删除后 expectedModCount 和 modCount 的值相同，这样在下一次 next()方法时，就不会报异常。<br>并发修改异常的意义在于保证迭代器获取到正确的元素。</p><h2 id="解决办法："><a href="#解决办法：" class="headerlink" title="解决办法："></a>解决办法：</h2><p>1、在迭代器中不使用集合的增加删除操作。修改操作没有影响（修改操作不会改变集合元素的个数）。<br>2、当需要在迭代过程中需要对集合增加元素时，可是采用 Iterator 的子类 ListIterator，采用 listIterator()方法，该方法会返回一个 ListItr 类(仅支持 List)的对象，该类提供了反向遍历及增加的方法。<img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/concurrentModified2.png#id=RMNER&originHeight=203&originWidth=451&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=hk86g&originHeight=203&originWidth=451&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="></p><h2 id="其他："><a href="#其他：" class="headerlink" title="其他："></a>其他：</h2><p><strong>1、</strong>当 next()方法获取到的是集合的倒数第二个元素的时候，使用集合的删除操作不会发生异常<br><img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/concurrentModifiued3.png#id=if5io&originHeight=324&originWidth=414&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=LY1kC&originHeight=324&originWidth=414&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="><br>此时是因为：<br>当遍历到倒数第二个元素时，此时 cursor 的值为 size-1（倒数第二个元素的下标索引为 size-2，next()方法执行后 cursor 会加 1），而在此时进行删除操作后，size 的值会减一，变的和 cursor 相同。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> cursor != SubList.<span class="keyword">this</span>.size;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>程序继续执行，hasnext()方法判断 cursor 和 size 相同，会返回 false，集合遍历将会终止。<br><strong>2、</strong>在 foreach 循环遍历集合时中也不能采用集合的增加删除方法。因为 foreach 循环底层也是通过迭代器进行遍历，如果修改，同样会报异常。<br><strong>3、</strong><br><img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/concurrentModified4.png#id=lLR1C&originHeight=493&originWidth=568&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=tvYwc&originHeight=493&originWidth=568&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=">**<img src="https://hexoimage.oss-cn-hangzhou.aliyuncs.com/hexobolg/java/concurrentModified5.png#id=Vbjti&originHeight=467&originWidth=588&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title=#id=Dp1yl&originHeight=467&originWidth=588&originalType=binary%E2%88%B6=1&rotation=0&showTitle=false&status=done&style=none&title="></p></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%EF%BC%8C%E5%87%BB%E7%A9%BF%EF%BC%8C%E9%9B%AA%E5%B4%A9/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%EF%BC%8C%E5%87%BB%E7%A9%BF%EF%BC%8C%E9%9B%AA%E5%B4%A9/" class="post-title-link" itemprop="url">缓存穿透，击穿，雪崩</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 10:57:18 10:57:18" itemprop="dateCreated datePublished" datetime="2021-03-15T10:57:18+08:00">2021-03-15 10:57:18</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>553</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>1 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="缓存穿透，击穿，雪崩"><a href="#缓存穿透，击穿，雪崩" class="headerlink" title="缓存穿透，击穿，雪崩"></a>缓存穿透，击穿，雪崩</h1><h1 id="1、缓存穿透"><a href="#1、缓存穿透" class="headerlink" title="1、缓存穿透"></a>1、缓存穿透</h1><h2 id="概念："><a href="#概念：" class="headerlink" title="概念："></a>概念：</h2><p>正常情况下，需要查询的数据都存在，当查询一个缓存和数据库都不存在的数据时，每次请求都会落在数据库里，这种情况成称为缓存穿透。</p><h2 id="问题："><a href="#问题：" class="headerlink" title="问题："></a>问题：</h2><p>缓存穿透一般会导致数据库压力增大。恶意攻击会击垮数据库。会绕过缓存。</p><h2 id="解决："><a href="#解决：" class="headerlink" title="解决："></a>解决：</h2><p>1、在接口增加参数校验，不合法的直接返回。<br>2、缓存空值，将对应 key 的 value 设置为空值，避免暴力攻击。同时将 key 失效时间设置短一些，避免影响正常使用。<br>3、在网关阈值，限制同 ip 访问量。<br>4、高级用户布隆过滤器。bloom filter，可以对 key 进行判断是否在数据库存在，不存在就直接返回，存在就查询出来，并刷新缓存。</p><h1 id="2、缓存击穿"><a href="#2、缓存击穿" class="headerlink" title="2、缓存击穿"></a>2、缓存击穿</h1><h2 id="概念：-1"><a href="#概念：-1" class="headerlink" title="概念："></a>概念：</h2><p>高并发系统中，大量请求一般会落在缓存中，但在某一时刻这个热点 key 过期了，此刻大量请求就会落在数据库。</p><h2 id="问题：-1"><a href="#问题：-1" class="headerlink" title="问题："></a>问题：</h2><p>会导致数据库压力增大，严重者击垮数据库。</p><h2 id="解决：-1"><a href="#解决：-1" class="headerlink" title="解决："></a>解决：</h2><p>1、设置热点 key 不过期。<br>2、加上分布式锁，每次只有拿到锁的线程可以去访问数据库。第一个线程查询到后就会缓存起来，后面线程从缓存中拿。</p><h1 id="3、缓存雪崩"><a href="#3、缓存雪崩" class="headerlink" title="3、缓存雪崩"></a>3、缓存雪崩</h1><h2 id="概念：-2"><a href="#概念：-2" class="headerlink" title="概念："></a>概念：</h2><p>某一时刻发生大规模缓存不可用问题，比如宕机，过期。</p><h2 id="问题：-2"><a href="#问题：-2" class="headerlink" title="问题："></a>问题：</h2><p>轻则查询变慢，重则大面积服务不可用。</p><h2 id="解决：-2"><a href="#解决：-2" class="headerlink" title="解决："></a>解决：</h2><p>1、采用分布式集群，减少宕机风险。<br>2、将 key 的失效时间设置为随机数，避免大量缓存同时失效。<br>3、采用本地缓存加限流逻辑。</p></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1/" class="post-title-link" itemprop="url">多线程间通信</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 10:56:38 10:56:38" itemprop="dateCreated datePublished" datetime="2021-03-15T10:56:38+08:00">2021-03-15 10:56:38</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>1.9k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>2 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="多线程间通信"><a href="#多线程间通信" class="headerlink" title="多线程间通信"></a>多线程间通信</h1><h1 id="1、案例"><a href="#1、案例" class="headerlink" title="1、案例"></a>1、案例</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.company;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NumberHolder</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> number;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">increase</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="number">0</span> != number) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 能执行到这里说明已经被唤醒</span></span><br><span class="line">        <span class="comment">// 并且number为0</span></span><br><span class="line">        number++;</span><br><span class="line">        System.out.print(number+<span class="string">&quot;-&quot;</span>);</span><br><span class="line">        <span class="comment">// 通知在等待的线程</span></span><br><span class="line">        notify();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">decrease</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="number">0</span> == number) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 能执行到这里说明已经被唤醒</span></span><br><span class="line">        <span class="comment">// 并且number不为0</span></span><br><span class="line">        number--;</span><br><span class="line">        System.out.print(number+<span class="string">&quot;-&quot;</span>);</span><br><span class="line">        notify();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IncreaseThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> NumberHolder numberHolder;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">IncreaseThread</span><span class="params">(NumberHolder numberHolder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.numberHolder = numberHolder;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">20</span>; ++i) &#123;</span><br><span class="line">            <span class="comment">// 进行一定的延时</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep((<span class="keyword">long</span>) Math.random() * <span class="number">10000</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 进行增加操作</span></span><br><span class="line">            numberHolder.increase();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DecreaseThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> NumberHolder numberHolder;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DecreaseThread</span><span class="params">(NumberHolder numberHolder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.numberHolder = numberHolder;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">20</span>; ++i) &#123;</span><br><span class="line">            <span class="comment">// 进行一定的延时</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep((<span class="keyword">long</span>) Math.random() * <span class="number">10000</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 进行减少操作</span></span><br><span class="line">            numberHolder.decrease();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        NumberHolder numberHolder = <span class="keyword">new</span> NumberHolder();</span><br><span class="line">        Thread t1 = <span class="keyword">new</span> IncreaseThread(numberHolder);</span><br><span class="line">        Thread t2 = <span class="keyword">new</span> DecreaseThread(numberHolder);</span><br><span class="line">        <span class="comment">// Thread t3 = new DecreaseThread(numberHolder);</span></span><br><span class="line">        <span class="comment">// Thread t4 = new DecreaseThread(numberHolder);</span></span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        <span class="comment">// t3.start();</span></span><br><span class="line">        <span class="comment">// t4.start();</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="2、分析"><a href="#2、分析" class="headerlink" title="2、分析"></a>2、分析</h1><p>此案例</p></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><div class="post-block"><article itemscope itemtype="http://schema.org/Article" class="post-content"><link itemprop="mainEntityOfPage" href="https://linqiankun.github.io/hexoblog/yuque/weidai/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%88%9B%E5%BB%BA/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/hexoblog/images/avatar.png"><meta itemprop="name" content="九分石人"><meta itemprop="description" content="my blogs"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Study"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"><a href="/hexoblog/yuque/weidai/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%88%9B%E5%BB%BA/" class="post-title-link" itemprop="url">多线程创建</a></h2><div class="post-meta-container"><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2021-03-15 10:55:53 10:55:53" itemprop="dateCreated datePublished" datetime="2021-03-15T10:55:53+08:00">2021-03-15 10:55:53</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar-check"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2024-05-14 16:20:04 16:20:04" itemprop="dateModified" datetime="2024-05-14T16:20:04+08:00">2024-05-14 16:20:04</time></span></div><div class="post-meta"><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="far fa-file-word"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>2.6k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="far fa-clock"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>2 分钟</span></span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="多线程创建"><a href="#多线程创建" class="headerlink" title="多线程创建"></a>多线程创建</h1><h1 id="1、线程的创建"><a href="#1、线程的创建" class="headerlink" title="1、线程的创建"></a>1、线程的创建</h1><h2 id="1-1、继承-Tread-类实现"><a href="#1-1、继承-Tread-类实现" class="headerlink" title="1.1、继承 Tread 类实现"></a>1.1、继承 Tread 类实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">myThread</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        myThread1 m1 = <span class="keyword">new</span> myThread1(<span class="string">&quot;你好1&quot;</span>);</span><br><span class="line">        m1.start();</span><br><span class="line">        myThread1 m2 = <span class="keyword">new</span> myThread1(<span class="string">&quot;你好2&quot;</span>);</span><br><span class="line">        m2.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//继承Thread类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">myThread1</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> tickets = <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">myThread1</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//doSomeThing</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">this</span>.tickets &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(<span class="keyword">this</span>.name + <span class="string">&quot;--------&quot;</span> + <span class="keyword">this</span>.tickets--);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="1-2、实现-Runnable-接口"><a href="#1-2、实现-Runnable-接口" class="headerlink" title="1.2、实现 Runnable 接口"></a>1.2、实现 Runnable 接口</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">myThreadtwo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aa = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        mythread1 m1 = <span class="keyword">new</span> mythread1(aa);</span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(m1,<span class="string">&quot;第一个&quot;</span>);</span><br><span class="line">        Thread t2 = <span class="keyword">new</span> Thread(m1,<span class="string">&quot;第二个&quot;</span>);</span><br><span class="line">        Thread t3 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                System.out.println(aa);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        t3.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//实现Runnable类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">mythread1</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> tickets = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">mythread1</span><span class="params">(<span class="keyword">int</span> t)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.tickets = t;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//doSomeThing</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"><span class="comment">//        synchronized (this) &#123;</span></span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">this</span>.tickets &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName() + <span class="string">&quot;--------&quot;</span> + <span class="keyword">this</span>.tickets--);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="keyword">this</span>);</span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="1-3、实现-Callable-接口"><a href="#1-3、实现-Callable-接口" class="headerlink" title="1.3、实现 Callable 接口"></a>1.3、实现 Callable 接口</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">myThreadThree</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aa = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        myThreadnew m1 = <span class="keyword">new</span> myThreadnew(aa);</span><br><span class="line">        FutureTask future = <span class="keyword">new</span> FutureTask(m1);</span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(future,<span class="string">&quot;第一个&quot;</span>);</span><br><span class="line">        Thread t2 = <span class="keyword">new</span> Thread(future,<span class="string">&quot;第二个&quot;</span>);</span><br><span class="line">        Thread t3 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> FutureTask(<span class="keyword">new</span> Callable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Object <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;));</span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        t3.start();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            future.get();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ExecutionException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//实现Callable类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">myThreadnew</span> <span class="keyword">implements</span> <span class="title">Callable</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> tickets = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">myThreadnew</span><span class="params">(<span class="keyword">int</span> t)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.tickets = t;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//doSomeThing</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">this</span>.tickets &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">&quot;--------&quot;</span> + <span class="keyword">this</span>.tickets--);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="2、创建方式的比较"><a href="#2、创建方式的比较" class="headerlink" title="2、创建方式的比较"></a>2、创建方式的比较</h1><p>如果一个类继承  Thread，则不适合资源共享。但是如果实现了  Runable  接口的话，则很容易的实现资源共享。<br>相对来说，实现 Runnable 接口比继承 Thread 好。个人感觉完成同一个任务实现接口比较方便，跑不同的任务，继承 Thread 比较方便。<br>采用匿名内部类使用 Runnable 接口，会隐式的印用当前 Activity，会造成内存泄露。</p><h3 id="1、实现-Runnable-的优势"><a href="#1、实现-Runnable-的优势" class="headerlink" title="1、实现 Runnable 的优势"></a>1、实现 Runnable 的优势</h3><p>可以避免 java 中的单继承的限制<br>线程池只能放入实现  Runable  或  callable  类线程，不能直接放入继承 Thread  的类</p><h3 id="2、两者都有的"><a href="#2、两者都有的" class="headerlink" title="2、两者都有的"></a>2、两者都有的</h3><p>适合多个相同的程序代码的线程去处理同一个资源<br>增加程序的健壮性，代码可以被多个线程共享，代码和数据独立</p></div><footer class="post-footer"><div class="post-eof"></div></footer></article></div><nav class="pagination"><a class="extend prev" rel="prev" href="/hexoblog/page/17/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/hexoblog/">1</a><span class="space">&hellip;</span><a class="page-number" href="/hexoblog/page/17/">17</a><span class="page-number current">18</span><a class="page-number" href="/hexoblog/page/19/">19</a><span class="space">&hellip;</span><a class="page-number" href="/hexoblog/page/24/">24</a><a class="extend next" rel="next" href="/hexoblog/page/19/"><i class="fa fa-angle-right" aria-label="下一页"></i></a></nav><script>window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }</script></div></main><footer class="footer"><div class="footer-inner"><div class="copyright">&copy; Tue Mar 02 2021 08:00:00 GMT+0800 (中国标准时间) – <span itemprop="copyrightYear">2025</span> <span class="with-love"><i class="fa fa-heart"></i> </span><span class="author" itemprop="copyrightHolder">九分石人</span></div><div class="wordcount"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-chart-line"></i> </span><span title="站点总字数">682k</span> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">10:20</span></span></div><div class="busuanzi-count"><span class="post-meta-item" id="busuanzi_container_site_uv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-user"></i> </span><span class="site-uv" title="总访客量"><span id="busuanzi_value_site_uv"></span> </span></span><span class="post-meta-item" id="busuanzi_container_site_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="site-pv" title="总访问量"><span id="busuanzi_value_site_pv"></span></span></span></div></div></footer><script size="300" alpha="0.6" zindex="-1" src="https://unpkg.com/ribbon.js@1.0.2/dist/ribbon.min.js"></script><script src="https://unpkg.com/animejs@3.2.1/lib/anime.min.js"></script><script src="https://unpkg.com/jquery@3.6.0/dist/jquery.min.js"></script><script src="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script><script src="https://unpkg.com/pangu@4.0.7/dist/browser/pangu.min.js"></script><script src="/hexoblog/js/utils.js"></script><script src="/hexoblog/js/motion.js"></script><script src="/hexoblog/js/next-boot.js"></script><script src="/hexoblog/js/bookmark.js"></script><script src="/hexoblog/js/local-search.js"></script><script>var mermaidElements = document.querySelectorAll('.mermaid');
if (mermaidElements.length) {
  NexT.utils.getScript('https://unpkg.com/mermaid@8.9.2/dist/mermaid.min.js', () => {
    mermaidElements.forEach(element => {
      const newElement = document.createElement('div');
      newElement.innerHTML = element.innerHTML;
      newElement.className = element.className;
      element.parentNode.replaceChild(newElement, element);
    });

    mermaid.init({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    }, '.mermaid');
  }, window.mermaid);
}</script><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script src="https://unpkg.com/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script><script>var options = {
  bottom: '64px',
  right: 'unset',
  left: '32px',
  time: '0.5s',
  mixColor: 'transparent',
  backgroundColor: 'transparent',
  buttonColorDark: '#100f2c',
  buttonColorLight: '#fff',
  saveInCookies: true,
  label: '🌓',
  autoMatchOsTheme: true
}
const darkmode = new Darkmode(options);
window.darkmode = darkmode;
darkmode.showWidget();</script></body></html>